import 'dart:io';
import 'dart:convert';
import 'package:crypto/crypto.dart';
import 'package:device_info_plus/device_info_plus.dart';
import 'package:sil_utils_package/sil_utils_package.dart';

Future<Map<String, dynamic>> getRequestEncryptionParamDictByParamDictType4(
    Map<String, dynamic> paramDict, String apiKey) async {
  if (apiKey.isEmpty) {
    print("apiKey");
    return paramDict;
  }

  // 添加时间戳
  int timeStamp = SilTimeUtils.currentTimeMillis() ~/ 1000;
  print("timeStamp = $timeStamp");
  paramDict['timestamp'] = timeStamp;

  // 将值为String类型的，去除两边的空格
  Map<String, dynamic> tempMap = Map();
  Map<String, dynamic> tempSignMap = Map(); // 需要签名的数组
  paramDict.forEach((key, value) {
    if (value is String) {
      value = value.trim();
    }
    tempMap[key] = value;

    // 参数为对象的,如果list、map不需要签名
    if (value is List || value is Map) {
    } else {
      tempSignMap[key] = value;
    }
  });

  paramDict = tempMap;

  String sign = getSignByParamDictVersionTow(tempSignMap, apiKey);
  if (!sign.isEmpty) {
    paramDict['sign'] = sign;
  }

  return paramDict;
}

/**
 * @description:  对参数进行签名
 * @return {
 * paramDict：参数
 * apiKey
 * }
 */
String getSignByParamDictVersionTow(
    Map<String, dynamic> paramDict, String apiKey) {
  if (paramDict.isEmpty) {
    print("空的 paramDict");
    return "";
  }

  List<String> keys = [];
  for (String key in paramDict.keys) {
    keys.add(key);
  }
  keys.sort((a, b) => a.compareTo(b));
  print("it = ${keys}");

  String resultParamStr = "";
  for (int i = 0; i < keys.length; i++) {
    String paramKey = keys[i];
    dynamic paramValue = paramDict[paramKey];
    if (i != keys.length - 1) {
      resultParamStr = "${resultParamStr}${paramKey}=${paramValue}&";
    } else {
      resultParamStr = "${resultParamStr}${paramKey}=${paramValue}";
    }
  }
  resultParamStr = "${resultParamStr}${apiKey}";

  String md5str = generate_MD5(resultParamStr);
  return md5str;
}

/**
 * @description:  获取设备信息
 * @return {type} 设备信息
 */
Future<dynamic> getDeviceInfo() async {
  DeviceInfoPlugin deviceInfo = new DeviceInfoPlugin();
  var dataInfo;
  if (Platform.isIOS) {
    print('IOS设备：');
    IosDeviceInfo iosInfo = await deviceInfo.iosInfo;
    dataInfo = iosInfo;
  } else if (Platform.isAndroid) {
    print('Android设备');
    AndroidDeviceInfo androidInfo = await deviceInfo.androidInfo;
    dataInfo = androidInfo;
  }
  return dataInfo;
}

// 获取设备的唯一标识 uuid
Future<String> platformUid() async {
  var data = await getDeviceInfo(), res;
  if (Platform.isIOS) {
    res = data.identifierForVendor;
  } else if (Platform.isAndroid) {
    res = data.androidId;
  }
  return res;
}

// md5 加密
String generate_MD5(String data) {
  var content = new Utf8Encoder().convert(data);
  var digest = md5.convert(content);

  return digest.toString();
  // 这里其实就是 digest.toString()
  // return hex.encode(digest.bytes);
}
